﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using RFDeviceNet;


namespace RFDeviceTester
{
    /// <summary>
    /// Логика взаимодействия для MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private ConnectionParams _connection;
        private readonly string _libVersion;
        private ObservableCollection<FuncResult> _results;
        private _UDP_DEVINFOBLOCK_PC_Net _udpPacket;

        public MainWindow()
        {
            InitializeComponent();
            _libVersion = RFDeviceObjectNet.RFDevice_GetVersionString();
            LibVersionLabel.Content = "Library version: " + _libVersion;
        }

        private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            _connection = new ConnectionParams();
            DataGridColumn c1 = new DataGridTextColumn
                {
                    Header = "Параметр",
                    Binding = new Binding("Parameter")
                };
            DataGridColumn c2 = new DataGridTextColumn
            {
                Header = "Значение",
                Binding = new Binding("Value")
            };
            InfoGrid.Columns.Add(c1);
            InfoGrid.Columns.Add(c2);
            _results = new ObservableCollection<FuncResult>();
            InfoGrid.ItemsSource = _results;
            RFDeviceObjectNet.Initialize();
        }

        private void ClickButton_OnClick(object sender, RoutedEventArgs e)
        {
            Go603Test();
        }

        private void Go603Test()
        {
            _results.Clear();
            var d = RF603DeviceNet.CreateRF603Device();
            d.BindNetworkAddress(1);
            d.OpenPort("COM6", 9600);
            var ps = new _RF60x_HELLO_ANSWER_Net();
            d.HelloCmd(1, ref ps);
            ushort value = 0;
            d.Measure(1, ref value);
            d.ClosePort();
        }

        private void Go620Test()
        {
            _results.Clear();
            UdpResList.Items.Clear();
            PointsList.Items.Clear();
            var bb = new byte[1];

            if (_udpPacket == null)
            {
                MessageBox.Show("Сначала получите пакет.");
                return;
            }
            bool connected;
            RF620DeviceNet d;
            try
            {
                d = RF620DeviceNet.CreateRF620Device(_udpPacket);
                connected = d.Connect();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fuck", ex.Message, MessageBoxButton.OK, MessageBoxImage.Asterisk);
                return;
            }
            
            _results.Add(new FuncResult
            {
                Parameter = "Подключен",
                Value = connected.ToString()
            });
            var tcpResBuf = new byte[0];
            var gotTcpResult  = d.GetResult(ref tcpResBuf);
            _results.Add(new FuncResult
            {
                Parameter = "TCP_GetResult",
                Value = gotTcpResult.ToString()
            });
            foreach (var b in tcpResBuf)
            {
                UdpResList.Items.Add(b.ToString(CultureInfo.InvariantCulture));
            }
            bool disconnected = d.Disconnect();
            _results.Add(new FuncResult
            {
                Parameter = "Отключен",
                Value = disconnected.ToString()
            });

            bool udpConnected = d.UDPConnect(ushort.Parse(Port620.Text), Ip620.Text);
            _results.Add(new FuncResult
            {
                Parameter = "UDP подключен",
                Value = udpConnected.ToString()
            });
            var buf = new byte[0];
            bool gotResult = d.UDPGetResult(ref buf);
            _results.Add(new FuncResult
            {
                Parameter = "UDP получен результат",
                Value = gotResult.ToString()
            });
            /*foreach (var b in buf)
            {
                UdpResList.Items.Add(b.ToString(CultureInfo.InvariantCulture));
            }*/
            var points = new float[0];
            ushort pointsCount = 0;
            ushort normResult = d.UDPGetNormalizedResult(ref points, ref pointsCount);
            _results.Add(new FuncResult
            {
                Parameter = "UDPGetNormalizedResult",
                Value = normResult.ToString(CultureInfo.InvariantCulture)
            });
            foreach (var point in points)
            {
                PointsList.Items.Add(point.ToString(CultureInfo.InvariantCulture));
            }
            PointsCountLabel.Content = pointsCount.ToString(CultureInfo.InvariantCulture);
            bool udpDisconnected =  d.UDPDisconnect();
            _results.Add(new FuncResult
            {
                Parameter = "UDPDisconnect",
                Value = udpDisconnected.ToString()
            });

            
            
        }

        class ConnectionParams
        {
            public string PortName { get; set; }
            public int ComPort { get; set; }
            public uint Speed { get; set; }
            public int Address { get; set; }

            public bool Check(string comPort, string speed, string address)
            {
                int icomPort;
                uint ispeed;
                int iaddress;
                //if (!int.TryParse(comPort, out icomPort))
                //    return false;
                if (!uint.TryParse(speed, out ispeed))
                    return false;
                if (!int.TryParse(address, out iaddress) && !string.IsNullOrEmpty(address))
                    return false;
                //ComPort = icomPort;
                PortName = comPort;
                Speed = ispeed;
                Address = iaddress;
                return true;
            }
        }

        class FuncResult
        {
            public string Parameter { get; set; }
            public string Value { get; set; } 
        }

        private void GetPacket_OnClick(object sender, RoutedEventArgs e)
        {
            var w = new PacketWorker();
            try
            {
                _udpPacket = w.GetUdpPcketFrom620();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            
            MessageBox.Show("Можно подключаться к устройству");
        }

        private void GetParamButton_OnClick(object sender, RoutedEventArgs e)
        {
            try
            {
                var value = GetParamValue();
                LaserLevelBox.Text = value.ToString(CultureInfo.InvariantCulture);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }

        private byte GetParamValue()
        {
            if (_udpPacket == null)
            {
                throw new Exception("Сначала получите пакет");
            }
            bool connected;
            RF620DeviceNet d;
            d = RF620DeviceNet.CreateRF620Device(_udpPacket);
            connected = d.Connect();
            if (!connected)
            {
                throw new Exception("Не удалось подключиться");
            }
            var val = d.GetLaserLevel();
            d.Disconnect();
            return val;
        }

        private void SetParamButton_OnClick(object sender, RoutedEventArgs e)
        {
            if (_udpPacket == null)
            {
                MessageBox.Show("Сначала получите пакет.");
                return;
            }
            bool connected;
            RF620DeviceNet d;
            try
            {
                d = RF620DeviceNet.CreateRF620Device(_udpPacket);
                connected = d.Connect();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fuck", ex.Message, MessageBoxButton.OK, MessageBoxImage.Asterisk);
                return;
            }
            if (!connected)
            {
                MessageBox.Show("Не удалось подключиться");
                return;
            }
            byte value;
            if (!byte.TryParse(LaserLevelBox.Text, out value))
            {
                MessageBox.Show("Введено некорректное значение");
                return;
            }
            if (value > 31)
            {
                MessageBox.Show("Значение не может быть больше 31");
                return;
            }
            var set = d.SetLaserLevel(value);
            MessageBox.Show(d.WriteParams() ? "Значение установлено" : "Не удалось установить значение");
            d.Disconnect();
        }
    }
}
